package cs.upt.awp.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import cs.upt.awp.data.City;
import cs.upt.awp.data.Country;

public class CityDAO {

	@Autowired
	SessionFactory sessionFactory;

	Session session = null;
	Transaction tx = null;    
	
	
	public City getEntityById(long id) throws Exception {
		
		session = sessionFactory.openSession();
		City country = (City) session.load(City.class, new Long(id));
		tx = session.getTransaction();
		session.beginTransaction();
		tx.commit();
		
		return country;
	}

	@SuppressWarnings("unchecked")	
	public List<City> getEntityList() throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<City> cities = session.createCriteria(
				City.class).list();
		tx.commit();
		session.close();
		return cities;
	}
	
	@SuppressWarnings("unchecked")	
	public List<City> getCitiesOfCountry(String countryCode) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<City> cities = session.createCriteria(
				City.class).add(Restrictions.like("country.code", countryCode)).addOrder(Order.asc("name")).list();
		tx.commit();
		session.close();
		return cities;
	}
	
}
